import {
	baseUrl,
	charterBaseUrl
} from './config'
import {
	showToast,
	showModalLogout
} from '../utils/index'
import axios from 'axios'


var request = axios.create({
	baseURL: baseUrl,
	// headers: {'Content-Type': 'application/x-www-form-urlencoded'},
	headers: {
		'Content-Type': 'application/json'
	},
	dataType: 'json' // 返回数据格式
})

const err = (error) => {
	return Promise.reject(error)
}

const memberLogin = (data) => {
	var dataForm = '';
	for(var key in data){
		dataForm += ((dataForm ? '&' : '')+key+'='+data[key])
	}
	return request({
		method: 'POST',
		url:charterBaseUrl+'/wxapp/member/login',
		data:dataForm,
		contentType:1
	})
}

const getToken = () => {
	 return new Promise((resolve, reject) => {
		uni.login({provider: 'weixin',success:async(res) =>{
		 	const userLoginRes = await memberLogin({
		 	  code: res.code,
		 	});
		 	const token = userLoginRes.data?.token;
		   
		 	resolve(token);
		 	// return token;
		}});
	 })
}

var loginPrm=null;

const busLogin = () =>{
	// debugger;
  if (loginPrm) return loginPrm;
  return (loginPrm = (async () => {
	  const storageToken = uni.getStorageSync('ltk');
	  if (storageToken) {
		return storageToken;
	  }else{
		var token1 = '';
		await getToken().then(token => {
			token1 = token;
			uni.setStorageSync('ltk', token);
		})
		return token1;
	  }
  })())
  // return loginPrm();
};

const requestAgain = (config) => {
	return request({
		...config
	})
}

// 请求拦截器
request.interceptors.request.use(async(config) => {
	if(config.url.indexOf('wxapp') > 0 || config.url.indexOf('wxpay') > 0){
		if(config.url.indexOf('/member/login') < 0){
			let token = await busLogin();
			console.info(9777,token)
			config.headers.wxappToken= token;
		}
	}else{
		if (uni.getStorageSync('xcxtoken')) {
			config.headers.xcxtoken = uni.getStorageSync('xcxtoken');
		}
	}
	
	if(config.contentType){//大巴车业务contentType需要改
		config.headers['Content-Type']="application/x-www-form-urlencoded"
	}

	if (config.method === 'POST') {
	} else {}
	return config
}, error => {
	return Promise.reject(error);
})

// 响应拦截器
request.interceptors.response.use((response) => {
	var pages = getCurrentPages();
	let isLoginPage = false;
	if (pages.length > 1) {
		if (pages[1].route.indexOf('login') > 0) {
			isLoginPage = true;
		}
	}
	console.log("=响应拦截=",response)
	// debugger;
	if (response.status == 200) {
		let retcode = response.data.retcode || '';
		// debugger;
		if (response.data.code == 200 || retcode == 0) {
			return response.data;
			
		} else if(retcode == 401 || retcode == -1){ //大巴车业务 retcode：401 token过期，retcode：-1请求错误
		
			console.log("=大巴车登录过期拦截=",response.data.retcode,response.data.retmsg)
			if(retcode == -1 && response.data.retmsg?.indexOf('POST') < 0 ){
				showToast(response.data.retmsg || "系统繁忙，请稍后再试！");
				return response.data;
			}
			loginPrm = null;
			uni.removeStorageSync('ltk');
			let res = requestAgain(response.config);
			return res.data;
			
		} else if(!retcode || retcode != 401){//网约车&大巴车其它状态码处理
			let haveMsg = uni.getStorageSync('haveShowModal');
			if (response.data.code === 403 && !isLoginPage && !haveMsg) {//网约车业务token过期
				showModalLogout('提示', '登录状态已过期，请重新登录！', false);
				
			}else{
				if(response.data.code != 403){
					showToast(response.data.msg || response.data.retmsg || "系统繁忙，请稍后再试！");
				}
			}

			return response.data;
			
		}
	} else {
		if (response.errMsg && response.errMsg.indexOf('jsapi has no permission') < 0) {
			// showToast(response.errMsg);
		}
		return Promise.reject(response.errMsg)
	}

}, err)

request.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			// url: baseUrl + buildURL(config.url, config.params, config.paramsSerializer),
			url:( config.url.indexOf('http') >= 0 ? '' : baseUrl ) 
			+ buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}

export default class Base {
	static get(url, params) {
		return request({
			method: 'GET',
			url,
			params
		})
	}
	static formGet(url,params){
		return request({
			method: 'GET',
			url,
			params,
			contentType:1
		})
	}
	static post(url, data, params) {
		return request({
			method: 'POST',
			url,
			data,
			params
		})
	}
	//大巴车业务的post请求，传输数据格式不同
	static formPost(url, data, params) {
		var dataForm = '';
			
		for(var key in data){
			dataForm += ((dataForm ? '&' : '')+key+'='+data[key])
		}
		
		return request({
			method: 'POST',
			url,
			data:dataForm,
			params,
			contentType:1
		})
	}
	static delete(url, params) {
		return request({
			method: 'DELETE',
			url,
			params
		})
	}
	static put(url, params) {
		return request({
			method: 'PUT',
			url,
			params
		})
	}
}
